#include "Player.h"
#include "ui_Player.h"
#include "playercontrols.h"
#include "videowidget.h"
#include <QBoxLayout>
#include <QMainWindow>
#include <QWidget>
#include <QDebug>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QPushButton>
#include <QFileDialog>
#include <QStandardPaths>
#include <QListWidget>
#include <QSlider>
#include <QLabel>


Player::Player(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Player)
{
    ui->setupUi(this);

    // 创建播放器
    m_player = new QMediaPlayer(this);
    // 创建播放列表
    m_playlist = new QMediaPlaylist();

    // 创建播放界面
    m_videoWidget = new VideoWidget(this);
    m_player->setVideoOutput(m_videoWidget);
    // 播放的显示列表
    m_playlistView = new QListWidget(this);

    // 创建打开文件按钮：
    QPushButton *openButton = new QPushButton(tr("Open"), this);
    connect(openButton, &QPushButton::clicked, this, [this](){
        open();
        qInfo()<<m_playlist;
        if (!m_playlist->isEmpty()) {
            m_playlistView->setCurrentRow(0);     // 默认第一个
            m_player->setPlaylist(m_playlist);
            m_player->play();
        }
    });

    // 全屏按钮：
    QPushButton *m_fullScreenButton = new QPushButton(tr("FullScreen"), this);
    // m_fullScreenButton->setCheckable(true);

    // 进度条：
    QSlider *m_slider = new QSlider(Qt::Horizontal, this);
    m_slider->setRange(0, m_player->duration() / 1000);

    QLabel *m_labelDuration = new QLabel(this);
    connect(m_slider, &QSlider::sliderMoved, this, &Player::seek);

    PlayerControls *controls = new PlayerControls(this);
    controls->setState(m_player->state());
    controls->setVolume(m_player->volume());
    controls->setMuted(controls->isMuted());

    connect(controls, &PlayerControls::play, m_player, &QMediaPlayer::play);
    connect(controls, &PlayerControls::pause, m_player, &QMediaPlayer::pause);
    connect(controls, &PlayerControls::stop, m_player, &QMediaPlayer::stop);
    connect(controls, &PlayerControls::next, m_playlist, &QMediaPlaylist::next);
    connect(controls, &PlayerControls::previous, m_playlist, &QMediaPlaylist::previous);
    connect(controls, &PlayerControls::changeVolume, m_player, &QMediaPlayer::setVolume);
    connect(controls, &PlayerControls::changeMuting, m_player, &QMediaPlayer::setMuted);
    connect(controls, &PlayerControls::changeRate, m_player, &QMediaPlayer::setPlaybackRate);
    connect(controls, &PlayerControls::stop, m_videoWidget, QOverload<>::of(&QVideoWidget::update));

    connect(m_player, &QMediaPlayer::stateChanged, controls, &PlayerControls::setState);
    connect(m_player, &QMediaPlayer::volumeChanged, controls, &PlayerControls::setVolume);
    connect(m_player, &QMediaPlayer::mutedChanged, controls, &PlayerControls::setMuted);

    // 全屏按钮：
    connect(m_fullScreenButton,&QPushButton::clicked,m_videoWidget,[=](){
        m_videoWidget->setFullScreen(1);
    });

    // 播放窗口的垂直布局：
    QBoxLayout *displayLayout = new QHBoxLayout;
    displayLayout->addWidget(m_videoWidget, 2);
    displayLayout->addWidget(m_playlistView);

    // 创建控制台
    QBoxLayout *controlLayout = new QHBoxLayout;
    controlLayout->setContentsMargins(0, 0, 0, 0);
    controlLayout->addWidget(openButton);
    controlLayout->addStretch(1);
    controlLayout->addWidget(controls);
    controlLayout->addStretch(1);
    controlLayout->addWidget(m_fullScreenButton);

    // 整个的layout
    QBoxLayout *layout = new QVBoxLayout;

    layout->addLayout(displayLayout);
    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->addWidget(m_slider);
    hLayout->addWidget(m_labelDuration);
    layout->addLayout(hLayout);

    layout->addLayout(controlLayout);
    setLayout(layout);
}

Player::~Player()
{
    delete ui;
}

static bool isPlaylist(const QUrl &url)         // Check for ".m3u" playlists.
{
    if (!url.isLocalFile())
        return false;
    const QFileInfo fileInfo(url.toLocalFile());
    return fileInfo.exists() && !fileInfo.suffix().compare(QLatin1String("m3u"), Qt::CaseInsensitive);
}

void Player::open()
{
    QFileDialog fileDialog(this);
    fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
    fileDialog.setWindowTitle(tr("Open Files"));
    QStringList supportedMimeTypes = m_player->supportedMimeTypes();
    if (!supportedMimeTypes.isEmpty()) {
        supportedMimeTypes.append("audio/x-m3u");       // MP3 playlists
        fileDialog.setMimeTypeFilters(supportedMimeTypes);
    }
    fileDialog.setDirectory(QStandardPaths::standardLocations(QStandardPaths::MoviesLocation).value(0, QDir::homePath()));
    if (fileDialog.exec() == QDialog::Accepted)
    {
        QList<QUrl> urls = fileDialog.selectedUrls();

        for (auto &url: urls) {
            m_playlistView->addItem(url.fileName());
            if (isPlaylist(url))
                m_playlist->load(url);
            else
                m_playlist->addMedia(url);
        }
    }
}

void Player::seek(int seconds)
{
    m_player->setPosition(seconds * 1000);
}
